using Microsoft.EntityFrameworkCore;
using MonitorPlatform.Data.Context;
using MonitorPlatform.Data.Configurations;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();

// Configure Entity Framework
builder.Services.AddDbContext<MonitoringDbContext>(options =>
{
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
    options.UseSqlServer(connectionString, sqlOptions =>
    {
        sqlOptions.EnableRetryOnFailure(
            maxRetryCount: 5,
            maxRetryDelay: TimeSpan.FromSeconds(30),
            errorNumbersToAdd: null);
        sqlOptions.CommandTimeout(60);
        sqlOptions.MigrationsAssembly("MonitorPlatform.Data");
    });

    // Enable sensitive data logging in development
    if (builder.Environment.IsDevelopment())
    {
        options.EnableSensitiveDataLogging();
        options.EnableDetailedErrors();
    }
});

// Add CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

// Configure OpenAPI/Swagger
builder.Services.AddOpenApi();
builder.Services.AddEndpointsApiExplorer();

// Configure JSON options
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
});

var app = builder.Build();

// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.MapOpenApi();
}

app.UseHttpsRedirection();
app.UseCors("AllowAll");

app.UseRouting();
app.MapControllers();

// Health check endpoint
app.MapGet("/health", () => Results.Ok(new { 
    Status = "Healthy", 
    Timestamp = DateTime.UtcNow,
    Version = "1.0.0"
}))
.WithName("HealthCheck")
.WithTags("Health");

// Monitoring API endpoints
app.MapPost("/api/monitoring/performance", async (MonitoringDbContext db, object performanceData) =>
{
    // TODO: Implement performance metrics collection
    return Results.Ok(new { Message = "Performance data received", Timestamp = DateTime.UtcNow });
})
.WithName("CollectPerformanceMetrics")
.WithTags("Monitoring");

app.MapPost("/api/monitoring/errors", async (MonitoringDbContext db, object errorData) =>
{
    // TODO: Implement error logging
    return Results.Ok(new { Message = "Error data received", Timestamp = DateTime.UtcNow });
})
.WithName("CollectErrors")
.WithTags("Monitoring");

app.MapPost("/api/monitoring/api-metrics", async (MonitoringDbContext db, object apiData) =>
{
    // TODO: Implement API metrics collection
    return Results.Ok(new { Message = "API metrics received", Timestamp = DateTime.UtcNow });
})
.WithName("CollectApiMetrics")
.WithTags("Monitoring");

app.MapPost("/api/monitoring/user-behavior", async (MonitoringDbContext db, object behaviorData) =>
{
    // TODO: Implement user behavior tracking
    return Results.Ok(new { Message = "User behavior data received", Timestamp = DateTime.UtcNow });
})
.WithName("CollectUserBehavior")
.WithTags("Monitoring");

// Database initialization
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<MonitoringDbContext>();
    try
    {
        // Ensure database is created
        await context.Database.EnsureCreatedAsync();
        Console.WriteLine("Database initialized successfully.");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error initializing database: {ex.Message}");
    }
}

app.Run();
